package com.ruoyi.project.jxy.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.jxy.domain.DownloadHistory;
import com.ruoyi.project.jxy.domain.ImgRecord;
import com.ruoyi.project.jxy.service.IDownloadHistoryService;
import com.ruoyi.project.jxy.service.IImgRecordService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 图片记录Controller
 *
 * @author ruoyi
 * @date 2020-09-07
 */
@RestController
@RequestMapping("/jxy/imgRecord")
public class ImgRecordController extends BaseController {
    @Autowired
    private IImgRecordService imgRecordService;
    @Autowired
    private IDownloadHistoryService downloadHistoryService;

    /**
     * 查询图片记录列表
     */
    @PreAuthorize("@ss.hasPermi('jxy:imgRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(ImgRecord imgRecord) {
        startPage();
        QueryWrapper<ImgRecord> queryWrapper = new QueryWrapper<ImgRecord>();
        if (StringUtils.isNotBlank(imgRecord.getRegion())) {
            queryWrapper.eq("region", imgRecord.getRegion());
        }
        if (StringUtils.isNotBlank(imgRecord.getTheme())) {
            queryWrapper.eq("theme", imgRecord.getTheme());
        }
        if (StringUtils.isNotBlank(imgRecord.getName())) {
            queryWrapper.like("name", imgRecord.getName());
        }
        if (StringUtils.isNotBlank(imgRecord.getSex())) {
            queryWrapper.eq("sex", imgRecord.getSex());
        }
        if (imgRecord.getAge() != null) {
            queryWrapper.eq("age", imgRecord.getAge());
        }
        if (StringUtils.isNotBlank(imgRecord.getPath())) {
            queryWrapper.eq("path", imgRecord.getPath());
        }
        if (StringUtils.isNotBlank(imgRecord.getDisplayName())) {
            queryWrapper.like("display_name", imgRecord.getDisplayName());
        }
        List<ImgRecord> list = imgRecordService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 导出图片记录列表
     */
    @PreAuthorize("@ss.hasPermi('jxy:imgRecord:export')")
    @Log(title = "图片记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ImgRecord imgRecord) {
        QueryWrapper<ImgRecord> queryWrapper = new QueryWrapper<ImgRecord>(imgRecord);
        List<ImgRecord> list = imgRecordService.list(queryWrapper);
        ExcelUtil<ImgRecord> util = new ExcelUtil<ImgRecord>(ImgRecord.class);
        return util.exportExcel(list, "imgRecord");
    }

    /**
     * 获取图片记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('jxy:imgRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(imgRecordService.getById(id));
    }

    /**
     * 新增图片记录
     */
    @PreAuthorize("@ss.hasPermi('jxy:imgRecord:add')")
    @Log(title = "图片记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ImgRecord imgRecord) throws IOException {
        imgRecord.setCreateTime(new Date());
        imgRecord.setCreateUser(SecurityUtils.getUsername());
        String md5 = DigestUtils.md5Hex(FileUtil.readBytes(FileUtil.newFile(imgRecord.getPath().replace("/profile", RuoYiConfig.getProfile()))));
        imgRecord.setFileMd5(md5);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("file_md5", imgRecord.getFileMd5());
        int check = imgRecordService.count(wrapper);
        BufferedImage bufferedImage = ImageIO.read(FileUtil.newFile(imgRecord.getPath().replace("/profile", RuoYiConfig.getProfile())));
        String resolution = bufferedImage.getWidth() + "x" + bufferedImage.getHeight();
        imgRecord.setResolution(resolution);
        imgRecord.setFileSize(FileUtil.newFile(imgRecord.getPath().replace("/profile", RuoYiConfig.getProfile())).length());
        if (check != 0) {
            return AjaxResult.error("该文件已存在");
        }
        return toAjax(imgRecordService.save(imgRecord) ? 1 : 0);
    }

    /**
     * 修改图片记录
     */
    @PreAuthorize("@ss.hasPermi('jxy:imgRecord:edit')")
    @Log(title = "图片记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ImgRecord imgRecord) throws IOException {
        imgRecord.setUpdateTime(new Date());
        imgRecord.setUpdateUser(SecurityUtils.getUsername());
        String md5 = DigestUtils.md5Hex(FileUtil.readBytes(FileUtil.newFile(imgRecord.getPath().replace("/profile", RuoYiConfig.getProfile()))));
        imgRecord.setFileMd5(md5);
        BufferedImage bufferedImage = ImageIO.read(FileUtil.newFile(imgRecord.getPath().replace("/profile", RuoYiConfig.getProfile())));
        String resolution = bufferedImage.getWidth() + "x" + bufferedImage.getHeight();
        imgRecord.setResolution(resolution);
        imgRecord.setFileSize(FileUtil.newFile(imgRecord.getPath().replace("/profile", RuoYiConfig.getProfile())).length());
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("file_md5", imgRecord.getFileMd5());
        wrapper.ne("id", imgRecord.getId());
        int check = imgRecordService.count(wrapper);
        if (check != 0) {
            return AjaxResult.error("该文件已存在");
        }
        return toAjax(imgRecordService.updateById(imgRecord) ? 1 : 0);
    }

    /**
     * 删除图片记录
     */
    @PreAuthorize("@ss.hasPermi('jxy:imgRecord:remove')")
    @Log(title = "图片记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(imgRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * 导出语音识别数据
     */
    @PreAuthorize("@ss.hasPermi('jxy:imgRecord:zip')")
    @Log(title = "图片识别打包", businessType = BusinessType.OTHER)
    @GetMapping("/zip")
    public AjaxResult zip(ImgRecord imgRecord) {
        QueryWrapper<ImgRecord> queryWrapper = new QueryWrapper<ImgRecord>();
        if (StringUtils.isNotBlank(imgRecord.getRegion())) {
            queryWrapper.eq("region", imgRecord.getRegion());
        }
        if (StringUtils.isNotBlank(imgRecord.getTheme())) {
            queryWrapper.eq("theme", imgRecord.getTheme());
        }
        if (StringUtils.isNotBlank(imgRecord.getName())) {
            queryWrapper.like("name", imgRecord.getName());
        }
        if (StringUtils.isNotBlank(imgRecord.getSex())) {
            queryWrapper.eq("sex", imgRecord.getSex());
        }
        if (imgRecord.getAge() != null) {
            queryWrapper.eq("age", imgRecord.getAge());
        }
        if (StringUtils.isNotBlank(imgRecord.getPath())) {
            queryWrapper.eq("path", imgRecord.getPath());
        }
        if (StringUtils.isNotBlank(imgRecord.getDisplayName())) {
            queryWrapper.like("display_name", imgRecord.getDisplayName());
        }
        List<ImgRecord> list = imgRecordService.list(queryWrapper);
        DownloadHistory downloadHistory = new DownloadHistory();
        BeanUtil.copyProperties(imgRecord, downloadHistory);
        downloadHistory.setId(null);
        downloadHistory.setType("4");
        downloadHistory.setCreateUser(SecurityUtils.getUsername());
        downloadHistory.setCreateTime(new Date());
        downloadHistoryService.save(downloadHistory);
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                String baseDir = RuoYiConfig.getProfile();
                //打包的文件夹名称
                String fileName = DateUtils.dateTimeNow();
                String fileDir = baseDir + "/download/" + fileName;
                String wavPath = fileDir + "/img";
                String txtPath = fileDir + "/txt";
                //新建wav文件夹
                FileUtil.mkdir(wavPath);
                //新建txt 文件夹
                FileUtil.mkdir(txtPath);
                for (ImgRecord record :
                        list) {
                    //复制文件
                    //每一个文件的真实地址
                    String realFilePath = record.getPath().replace("/profile", baseDir);
                    //复制音频文件
                    FileUtil.copy(realFilePath, wavPath, true);
                    //获取文件名
                    String name = record.getDisplayName().substring(0, record.getDisplayName().indexOf("."));
                    //生成txt 文件
                    FileUtil.writeString(record.getContent(), FileUtil.newFile(txtPath + "/" + name + ".txt"), Charset.defaultCharset());
                }
                File zip = ZipUtil.zip(fileDir);
                //压缩包真实名称
                String zipPath = zip.getAbsolutePath();
                String zipName = zip.getName();
                //转换为可下载路径
                String downloadPath = zipPath.replace(baseDir, "/profile");
                downloadHistory.setPath(downloadPath);
                downloadHistory.setDisplayName(zipName);
                downloadHistoryService.updateById(downloadHistory);
            }
        });
        return AjaxResult.success();
    }
}
